<template>
  <div class="environment-monitor">
    <div class="header-title">
      <dv-decoration-3 style="width:100px;height:20px;" />
      <div class="monitor-title">智慧大棚实时环境监测</div>
      <dv-decoration-3 style="width:100px;height:20px;" />
    </div>
    <div class="monitor-gauges">
      <div class="gauge-item">
        <div class="gauge-title">空气温度</div>
        <div ref="tempGaugeRef" class="gauge-chart"></div>
      </div>
      <div class="gauge-item">
        <div class="gauge-title">空气湿度</div>
        <div ref="humidityGaugeRef" class="gauge-chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { get } from '@/utils/request'
import router from '@/router'

// 图表实例
let tempGauge = null
let humidityGauge = null

// 使用 ref 获取 DOM 元素
const tempGaugeRef = ref(null)
const humidityGaugeRef = ref(null)

// 处理窗口大小改变
const handleResize = () => {
  tempGauge?.resize()
  humidityGauge?.resize()
}

// 初始化温度仪表盘
const initTempGauge = () => {
  if (tempGaugeRef.value) {
    tempGauge?.dispose()
    tempGauge = echarts.init(tempGaugeRef.value)
    const option = {
      series: [{
        type: 'gauge',
        min: 0,
        max: 30,
        splitNumber: 10,
        radius: '100%',
        axisLine: {
          lineStyle: {
            width: 10,
            color: [
              [0.7, '#03d3ec'],
              [1, '#ff6e76']
            ]
          }
        },
        pointer: {
          itemStyle: {
            color: '#03d3ec'
          }
        },
        axisTick: {
          distance: -10,
          length: 8,
          lineStyle: {
            color: '#fff',
            width: 2
          }
        },
        splitLine: {
          distance: -10,
          length: 12,
          lineStyle: {
            color: '#fff',
            width: 3
          }
        },
        axisLabel: {
          color: '#03d3ec',
          distance: 25,
          fontSize: 12
        },
        detail: {
          valueAnimation: true,
          formatter: '{value} °C',
          color: '#03d3ec',
          fontSize: 24,
          offsetCenter: [0, '70%']
        },
        data: [{
          value: 0
        }]
      }]
    }
    tempGauge.setOption(option)
  }
}

// 初始化湿度仪表盘
const initHumidityGauge = () => {
  if (humidityGaugeRef.value) {
    humidityGauge?.dispose()
    humidityGauge = echarts.init(humidityGaugeRef.value)
    const option = {
      series: [{
        type: 'gauge',
        min: 0,
        max: 120,
        splitNumber: 10,
        radius: '100%',
        axisLine: {
          lineStyle: {
            width: 10,
            color: [
              [0.8, '#03d3ec'],
              [1, '#ff6e76']
            ]
          }
        },
        pointer: {
          itemStyle: {
            color: '#03d3ec'
          }
        },
        axisTick: {
          distance: -10,
          length: 8,
          lineStyle: {
            color: '#fff',
            width: 2
          }
        },
        splitLine: {
          distance: -10,
          length: 12,
          lineStyle: {
            color: '#fff',
            width: 3
          }
        },
        axisLabel: {
          color: '#03d3ec',
          distance: 25,
          fontSize: 12
        },
        detail: {
          valueAnimation: true,
          formatter: '{value} %RH',
          color: '#03d3ec',
          fontSize: 24,
          offsetCenter: [0, '70%']
        },
        data: [{
          value: 0
        }]
      }]
    }
    humidityGauge.setOption(option)
  }
}

// 获取最新数据
const fetchLatestData = async () => {
  try {
    // 确保有token
    const token = localStorage.getItem('token')
    if (!token) {
      console.log('No token available, skipping request')
      return
    }

    // 获取最新的空气温度
    const tempResponse = await get('/at/current')
    if (tempResponse && tempGauge) {
      tempGauge.setOption({
        series: [{
          data: [{
            value: tempResponse.value
          }]
        }]
      })
    }

    // 获取最新的空气湿度
    const humidityResponse = await get('/ah/current')
    if (humidityResponse && humidityGauge) {
      humidityGauge.setOption({
        series: [{
          data: [{
            value: humidityResponse.value
          }]
        }]
      })
    }
  } catch (error) {
    if (error.response?.status === 401) {
      // 处理401错误
      router.push('/login')
    } else {
      console.error('Failed to fetch environment data:', error)
    }
  }
}

// 定时刷新数据
let refreshTimer = null;

onMounted(() => {
  initTempGauge()
  initHumidityGauge()
  // 延迟执行第一次数据获取
  setTimeout(fetchLatestData, 500)
  // 设置定时刷新，每3000秒更新一次数据
  refreshTimer = setInterval(fetchLatestData, 3000000)
  
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  clearInterval(refreshTimer) // 清除定时器
  tempGauge?.dispose()
  humidityGauge?.dispose()
  tempGauge = null
  humidityGauge = null
})
</script>

<style lang="scss" scoped>
.environment-monitor {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .header-title {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;

    .monitor-title {
      font-size: 14px;
      color: #03d3ec;
      white-space: nowrap;
      margin: 0 10px;
    }
  }

  .monitor-gauges {
    display: flex;
    justify-content: space-around;
    height: calc(100% - 30px);

    .gauge-item {
      width: 45%;
      height: 100%;

      .gauge-title {
        text-align: center;
        color: #ffffff;
        font-size: 14px;
        margin-bottom: 10px;
      }

      .gauge-chart {
        width: 100%;
        height: calc(100% - 24px);
      }
    }
  }
}
</style> 